package com.cskaoyan.shopping.service.remote;

import com.cskaoyan.mall.api.OrderProductService;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @auther cskaoyan
 * @date 2022/5/18:10:21
 */
@RestController
public class OrderProductServiceImpl implements OrderProductService {


    @Autowired
    ICartService iCartService;

    @Autowired
    ItemMapper itemMapper;

    /**
     * 清空指定用户的购物车缓存(用户下完订单之后清理）
     */
    @RequestMapping(value = "/rpc/items", method = RequestMethod.DELETE)
    @Override
    public ClearCartItemResponse clearCartItemByUserID(@RequestBody ClearCartItemRequest request) {

        ClearCartItemResponse clearCartItemResponse = iCartService.clearCartItemByUserID(request);
        return clearCartItemResponse;
    }

    @Override
    @RequestMapping("reduce/stocknum")
    public Boolean reduceStockNum(Long productId, Long productNum) {

        Item item = new Item();
        item.setId(productId);

        // 查出当前商品的信息

        Item item1 = itemMapper.selectByPrimaryKey(productId);
        item.setLimitNum(item1.getLimitNum() - productNum.intValue());
        item.setNum(item1.getNum() - productNum.intValue());
        item.setUpdated(new Date());
        item.setCreated(new Date());

        int affectedRows = itemMapper.updateByPrimaryKeySelective(item);

        if (affectedRows != 1){

            throw new BizException(SysRetCodeConstants.DB_EXCEPTION.getCode(),SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }

        return true;
    }


    @GetMapping("/update/itemNum")
    @Override
    public Boolean updateItemNum(Long itemId, Long newStockCount) {

        Item item = new Item();
        item.setId(itemId);
        item.setNum(newStockCount.intValue());
        item.setLimitNum(newStockCount.intValue());
        int i = itemMapper.updateByPrimaryKeySelective(item);

        if (i == 1) {
            return true;
        }
        return false;
    }
}
